
<template>
    <el-form-item :label="label"  v-if="label" class='formitem'>
        <el-input-number v-model="currentValue" @change="handleChange" :min="min" :max="max" ></el-input-number>
    </el-form-item>
    <div v-else class="el-form-item__content formitem">
          <el-input-number v-model="currentValue" @change="handleChange" :min="min" :max="max" ></el-input-number>
     </div>
</template>
 
<script>
    export default {
        props:{
            'max':Number,
            'min':Number,
            'value':Number,
            'label':String
            },
        name: "myInputNumber",
        data(){
            return {
                currentValue:this.value
            }
        },
        watch:{
            currentValue: function (val) { //currentValue值变动就向父组件传值
                this.$emit('input',val);
                this.$emit('on-change',val);
            },
            value:function (val) { //对值进行验证
                this.updataValue(val);
            }
        },
        mounted(){
            this.updataValue(this.value);
        },
        methods:{
            handleDown: function () {  //加法
                if(this.currentValue <= this.min){
                    return;
                }else{
                    this.currentValue -= 1;
                }
            },
            handleUp: function () { //减法
                if(this.currentValue >= this.max){
                    return;
                }else{
                    this.currentValue += 1;
                }
            },
            updataValue: function (val) {
                if(val > this.max){val = this.max}
                if(val < this.min){val = this.min}
                this.currentValue = val;
 
            },
            handleChange: function (event) {  //对值进行验证
                var val = event.target.value.trim();
                var max = this.max;
                var min = this.min;
                if(this.isNumber(val)){
                    val = Number(val);
                    this.currentValue = val;
                    if(val > max){
                        this.currentValue = max;
                    }else if(val < min){
                        this.currentValue = min;
                    }
                }else{
                    this.currentValue = 0;
                }
            },
            isNumber: function (value) {
                return (/^\-?[0-9]+$/).test(value + '');
            }
        }
    }
</script>
<style scoped>
.formitem{
    margin-left:35px;
}
</style>